//
//  HYUserInfo.m
//  HYChatProject
//
//  Created by erpapa on 16/4/20.
//  Copyright © 2016年 erpapa. All rights reserved.
//

#import "HYLoginInfo.h"
#import "HYXMPPManager.h"

#define kUser @"user"
#define kPassword @"password"
//#define kHostName @"hostName"
//#define kHostPort @"hostPort"
#define kLogon @"logon"
#define kSuperior @"superior"

@implementation HYLoginInfo

static HYLoginInfo *instance;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    // dispatch_once是线程安全的，onceToken默认为0
    static dispatch_once_t onceToken;
    // dispatch_once宏可以保证块代码中的指令只被执行一次
    dispatch_once(&onceToken, ^{
        // 在多线程环境下，永远只会被执行一次，instance只会被实例化一次
        instance = [super allocWithZone:zone];
    });
    
    return instance;
}

/**
 *  单例
 */
+ (instancetype)sharedInstance
{
    if (instance == nil) {
        instance = [[self alloc] init];
        [instance loadUserInfoFromSanbox];
    }
    return instance;
}

/**
 *  保存用户数据
 */
- (void)saveUserInfoToSanbox{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:_user forKey:kUser];
    [defaults setObject:_password forKey:kPassword];
    [defaults setObject:_superior forKey:kSuperior];
//    [defaults setObject:_hostName forKey:kHostName];
//    [defaults setInteger:_hostPort forKey:kHostPort];
    [defaults setBool:_logon forKey:kLogon];
    [defaults synchronize];
}

/**
 *  获取用户数据
 */
- (void)loadUserInfoFromSanbox{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.user = [defaults objectForKey:kUser];
    self.password = [defaults objectForKey:kPassword];
    self.logon = [defaults boolForKey:kLogon];
    self.superior = [defaults objectForKey:kSuperior];
//    NSString *hostName = [defaults objectForKey:kHostName];
//    NSInteger hostPort = [defaults integerForKey:kHostPort];
    //self.hostName = hostName.length ? hostName : kDomain;
//    self.hostPort = hostPort ? hostPort : kPort;
//    self.hostName = kHost;
//    self.hostPort = kPort;
}

- (XMPPJID *)jid
{
    return [XMPPJID jidWithUser:_user domain:kDomain resource:kResource];
}

- (NSString *)nickNameForJid:(XMPPJID *)jid
{
    NSString *str = [self.nickNameDict objectForKey:jid.bare];
    if (str.length == 0) {
        str = [[HYXMPPManager sharedInstance] getNicknameFromJID:jid];
    }
    return str;
}

- (void)saveNickNameDictToSanbox
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:_nickNameDict forKey:@"nickNameDict"];
    [defaults synchronize];
}

-(void)setNickName:(NSString *)nickName forJid:(XMPPJID *)jid
{
    if ([nickName rangeOfString:@"@172.104.94.34"].location!=NSNotFound) {
        nickName = [nickName substringToIndex:[nickName rangeOfString:@"@"].location];
    }
    [self.nickNameDict setObject:nickName forKey:jid.bare];
    [self saveNickNameDictToSanbox];
}

- (NSMutableDictionary *)nickNameDict
{
    if (_nickNameDict == nil) {
        _nickNameDict = [[[NSUserDefaults standardUserDefaults] objectForKey:@"nickNameDict"] mutableCopy];
        if (_nickNameDict == nil) {
            _nickNameDict = [NSMutableDictionary dictionary];
        }
    }
    return _nickNameDict;
}

-(void)saveGroupImagesToSanbox
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.groupImages forKey:@"GroupImages"];
    [defaults synchronize];
}

-(NSMutableDictionary *)groupImages
{
    if (!_groupImages) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults objectForKey:@"GroupImages"]) {
            _groupImages = [NSMutableDictionary dictionaryWithDictionary:[defaults objectForKey:@"GroupImages"]];
        }else{
            _groupImages = [NSMutableDictionary dictionary];
        }
    }
    return _groupImages;
}

- (void)saveGroupImage:(UIImage *)image withJidU:(NSString *)jidUser{
    
    NSData *imageData = UIImagePNGRepresentation(image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * imageName = [NSString stringWithFormat:@"%@.png",jidUser];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:imageName]; //Add the file name
    BOOL result = [imageData writeToFile:filePath atomically:YES];
    
    if (result == YES) {
        [self.groupImages setObject:imageName forKey:jidUser];
        [self saveGroupImagesToSanbox];
    }
}

- (UIImage *)getGroupImageWithJidU:(NSString *)jidUser {
    
    if ([self.groupImages objectForKey:jidUser]) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[self.groupImages objectForKey:jidUser]]; //Add the file name
        UIImage *img = [UIImage imageWithContentsOfFile:filePath];
        if (!img) {
            [self.groupImages removeObjectForKey:jidUser];
            [self saveGroupImagesToSanbox];
        }
        return img;
    }
    return nil;
}
@end
